import json
import datetime
from typing import Any
from typing import List
from typing import Union
from apis import api_routes
from sqlalchemy import desc
from sqlalchemy import and_
from sqlalchemy import text
from flask import abort, g, request, jsonify
from models.course.course import Course
from models.course.serial import Serial
from models.order.tasks import Tasks
from models.course.detailed import Detailed
from security.decoration import certification


@api_routes.route("/course", methods=["DELETE"])
@certification(auth=True, role=None)
def func_course_delete_api():
    """
    删除产品SN全部信息，完成API开发
    http://127.0.0.1:8080/api/course
    Content-Type=application/json
    methods=["DELETE"]
    {
    "course_id":    int    产品SN数据库ID
    }
    :return:
        {'status': 200, "msg": "删除产品信息成功"}
     ---
    tags:
      - 生产产品管理
    """
    data: dict = request.get_json()
    course_id: int = data.get("course_id")
    if not course_id:
        abort(400)

    course: Course = g.session.query(Course).filter(Course.id == course_id).first()
    if course is None:
        return jsonify({'status': 4000, "msg": "没有找到产品清单"})

    task_id = course.tasks_id

    g.session.query(Serial).filter(Serial.serial == course.sequence).delete()
    g.session.query(Detailed).filter(Detailed.sequence == course.sequence).delete()
    g.session.query(Course).filter(Course.sequence == course.sequence).delete()
    g.session.commit()

    db_task: Tasks = g.session.query(Tasks).filter(Tasks.id == task_id).first()
    count = g.session.query(Course.id).filter(Course.tasks_id == task_id).count()
    db_task.totals = count

    count = g.session.query(Course.id).filter(and_(Course.tasks_id == task_id, Course.mark == 1)).count()
    db_task.actual = count
    g.session.commit()
    return jsonify({'status': 200, "msg": "删除产品信息成功"})
